﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NPlot;
using Peltarion.Maths;

namespace EKG
{
    public partial class Form1 : Form
    {
        
        Peltarion.Deployed.EKGNET en = new Peltarion.Deployed.EKGNET();

        public Form1()
        {
            InitializeComponent();
        }

        private int step = 0;

        private void Form1_Load(object sender, EventArgs e)
        {
            QRSxtract q = new QRSxtract("c:\\tmp\\snimci\\100.dat");
            ArrayList qrs_int = q.List;

       /*     en.Set_CSV(14, 670, 245, 347, 181, 41, 0);
            en.StepEpoch();

            Matrix m = en.FunctionLayer4_Port0;
            if (m.Data[0] < 1.3)
                MessageBox.Show("ANOMALIJA");
            else MessageBox.Show("OK"); */

     //       String inFile = "c:\\100.dat";
      //      ReadData(inFile); 


            StreamReader s = new StreamReader("C:\\tmp\\ecg2\\100.txt");
            String line;
            ArrayList values = new ArrayList();
            ArrayList times = new ArrayList();

            while((line = s.ReadLine()) !=null )
            {
                string[] vals = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                ArrayList vals2 = new ArrayList();
                foreach (var val in vals)
                {
                    if (val!="\t")
                    {
                        vals2.Add(val);
                    }
                }
                string hepek = (string)vals2[2];
                double hepek2 = Double.Parse(hepek.Trim());
                values.Add(hepek2);
                string[] milis = ((string)vals2[0]).Trim().Split(':');
                double mili = Double.Parse(milis[1].Replace(".",","));
                if (milis[0] != "0") mili = mili + 60 * double.Parse(milis[0]);
                times.Add(mili);
                           
            }

            doPlotData(values, times, qrs_int);
            plotPanel.Width = values.Count;
            timer1.Start(); 
        }

 

        private void doPlotData(ArrayList a,ArrayList time, ArrayList qrs)
        {
            plotPanel.Clear();
            //Add a background grid for better chart readability.
            Grid grid = new Grid();
            grid.VerticalGridType = Grid.GridType.Coarse;
            grid.HorizontalGridType = Grid.GridType.Coarse;
            grid.MajorGridPen = new Pen(Color.LightGray, 1.0f);

            plotPanel.Add(grid);


            List<double> balanceAxis = new List<double>();
            for (int i = 0; i < (time.Count); i++)
                balanceAxis.Add(Convert.ToDouble(time[i]));
               // balanceAxis.Add( i * double.Parse("0,008"));

            plotPanel.Add(AddPlot(a, Color.Black, balanceAxis));

            //plotPanel.Add(AddPlot(a.GetRange(40, 100), Color.Red, balanceAxis.GetRange(40, 100)));



        /*     for (int i = 0; i < (qrs.Count); i++)
             {
                 x_qrs_p.Add(Convert.ToDouble(((FFactor)qrs[i]).P.Millisecond));
               //  x_qrs_p.Add(Convert.ToDouble(((FFactor)qrs[i]).T2.Millisecond));
                 x_qrs_p_h.Add(800);
                 x_qrs_p_h.Add(800);
                 plotPanel.Add(AddPlot2(x_qrs_p_h, Color.Red, x_qrs_p));
               //  x_qrs_p_h.Clear();
             } */
            // Izmedju 73 i 74
            for (int i = 0; i < 300 ; i++)
            {

                    List<double> x_qrs_p_h = new List<double>();
                    List<double> x_qrs_p = new List<double>();
                    double m1 = 60 * double.Parse(((FFactor)qrs[i]).N.ToString("mm"));
                    double N = double.Parse(((FFactor)qrs[i]).N.ToString("s,fff")) + m1;
                    double m2 = 60 * double.Parse(((FFactor)qrs[i]).P.ToString("mm"));
                    double P = double.Parse(((FFactor)qrs[i]).P.ToString("s,fff")) + m2;
                    x_qrs_p_h.Add(800);
                    x_qrs_p_h.Add(800);
                    x_qrs_p.Add(N);
                    x_qrs_p.Add(P);

                    bool isAnomal = CheckECG_NN((FFactor)qrs[i]);
                    if (isAnomal) debug.Text = debug.Text + "Anomalija na: " + (i + 3).ToString() + Environment.NewLine;
                    Color c = (isAnomal) ? Color.Red : Color.ForestGreen;
                    plotPanel.Add(AddPlot2(x_qrs_p_h, c, x_qrs_p));
 

            }

            Font fnt = new Font("Verdana", 8F, FontStyle.Italic, GraphicsUnit.Point);

            ArrayList pravi = new ArrayList();
            pravi.Add(8);
            pravi.Add(231);
            pravi.Add(259);
            foreach (int inw in pravi)
            {
                string mystring = @"Anomalija na: " + inw;
                int mps = debug.Find(mystring);
                debug.SelectionStart = mps;
                debug.SelectionLength = mystring.Length;
                debug.SelectionFont = fnt;
                debug.SelectionColor = Color.Red;
            }


          //  plotPanel.Add(AddPlot(b, Color.Red, balanceAxis));
            //       plotPanel.Add(AddPlot(tmixBwValues, Color.Green, balanceAxis)); 

          //  plotPanel.Draw(g, new Rectangle(20, 20, 100, 200));

            plotPanel.ShowCoordinates = true;
            plotPanel.YAxis1.Label = "Amplituda";
            plotPanel.YAxis1.LabelOffsetAbsolute = true;
            plotPanel.YAxis1.LabelOffset = 40;

            plotPanel.XAxis1.Label = "Vrijeme";
            plotPanel.XAxis1.LabelOffsetAbsolute = true;
            plotPanel.XAxis1.LabelOffset = 40;
            plotPanel.Padding = 5;

            plotPanel.Refresh();
        }

        private bool CheckECG_NN(FFactor priv)
        {
            if (priv.PR.TotalMilliseconds > 0 && priv.PR.TotalMilliseconds < 1000 &&
                                    priv.QRS_ST.TotalMilliseconds > 0 && priv.QRS_ST.TotalMilliseconds < 1000 &&
                                    priv.QT.TotalMilliseconds > 0 && priv.QT.TotalMilliseconds < 1000 &&
                                    priv.RS.TotalMilliseconds > 0 && priv.RS.TotalMilliseconds < 1000 &&
                                    priv.RT.TotalMilliseconds > 0 && priv.RT.TotalMilliseconds < 1000 &&
                                    priv.ST.TotalMilliseconds > 0 && priv.ST.TotalMilliseconds < 1000)
            {
                en.Set_CSV(priv.RS.TotalMilliseconds, priv.PR.TotalMilliseconds, priv.RT.TotalMilliseconds, priv.QT.TotalMilliseconds, priv.ST.TotalMilliseconds, priv.QRS_ST.TotalMilliseconds, 0);
                en.StepEpoch();
                
                Matrix m = en.FunctionLayer4_Port0;

                return (m.Data[0] < 1.3);
            } 
            else return (priv.Type=="0");
        }

        private LinePlot AddPlot(object ds, Color c, List<double> balanceAxis)
        {
            LinePlot pcapPacketsPlot = new LinePlot(ds);
            pcapPacketsPlot.Pen = new Pen(c, 1);

            pcapPacketsPlot.AbscissaData = balanceAxis;

            return pcapPacketsPlot;
        }

        private LinePlot AddPlot2(object ds, Color c, List<double> balanceAxis)
        {
            LinePlot pcapPacketsPlot = new LinePlot(ds);
            pcapPacketsPlot.Pen = new Pen(c, 4);

            pcapPacketsPlot.AbscissaData = balanceAxis;

            return pcapPacketsPlot;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            step += 5;
            panel1.AutoScrollPosition = new Point(step,0);
        }


        private void ReadData(string fileName)
        {
            ArrayList a = new ArrayList();
            long fileLength = 0;
            FileStream file;
            BinaryReader reader;
            int channel = Convert.ToInt16(1);


            file = new FileStream(fileName, FileMode.Open);
            reader = new BinaryReader(file);

            fileLength = file.Length;
            short flag = 0;
            long low = 0, high = 0;
            byte[] buf = { 0, 0, 0 };
            long cnt1 = fileLength;
            for (int i = 0; i < cnt1; i++)
            {
                for (short j = 1; j <= 2; j++)
                {
                    switch (flag)
                    {
                        case 0:
                            try
                            {
                                buf = reader.ReadBytes(3);
                            }
                            catch (Exception)
                            {
                                return;
                            }
                            low = buf[1] & 0x0F;
                            high = buf[1] & 0xF0;
                            if (channel == j)
                                if (low > 7)
                                {
                                    a.Add(Convert.ToDouble(buf[0] + (low << 8) - 4096));
                                    //  System.Threading.Thread.Sleep(1);
                                }
                                else
                                {

                                    a.Add(Convert.ToDouble((buf[0] + (low << 8) - 1024) * 0.005));
                                }// System.Threading.Thread.Sleep(1);
                            flag = 1;
                            break;
                        case 1:
                            if (channel == j)
                                if (high > 127)
                                {

                                    a.Add(Convert.ToDouble(buf[2] + (high << 4) - 4096));
                                }
                                // while (!CirkularniBuffer.Write(Convert.ToDouble(buf[2] + (high << 4) - 4096)));
                                //   System.Threading.Thread.Sleep(1);
                                else
                                {
                                    a.Add(Convert.ToDouble((buf[2] + (high << 4) - 1024) * 0.005));
                                    //   System.Threading.Thread.Sleep(1);
                                }
                            flag = 0;
                            break;
                    }
                }
            }

            doPlotData(a, a,a);
            //    System.Threading.Thread.Sleep(1);
        }


    }
}
